package com.xin.di.uav.applet.user.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.xin.di.uav.applet.request.AddAddressRequest;
import com.xin.di.uav.applet.resp.UserInfoResponse;
import com.xin.di.uav.common.awt.JwtUtil;
import com.xin.di.uav.common.utils.IdUtils;
import com.xin.di.uav.common.utils.PhoneEncoderUtil;
import com.xin.di.uav.operate.rest.UserRest;
import com.xin.di.uav.common.response.user.UserResponse;
import com.xin.di.uav.common.utils.Rs;
import com.xin.di.uav.user.entity.User;
import com.xin.di.uav.user.entity.UserExtra;
import com.xin.di.uav.user.mapper.UserExtraMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/sys/user/")
public class UserController {

    @Autowired
    private UserRest userRest;
    @Autowired
    private UserExtraMapper userExtraMapper;

    @GetMapping("get-user-info")
    public Rs<UserResponse> getByUserId() {
        return Rs.success(userRest.getByUserId());
    }

    @PostMapping("add-address")
    public Rs<Void> addAddress(@RequestBody @Valid AddAddressRequest addAddressRequest) {
        String userId = JwtUtil.getUserId();
        UserExtra userExtra = userExtraMapper.selByUserId(userId);
        if (ObjectUtils.isEmpty(userExtra)) {
            //插入
            userExtra = new UserExtra();
            userExtra.setId(IdUtils.getId());
            userExtra.setUserId(userId);
            userExtra.setReceiveName(addAddressRequest.getReceiveName());
            userExtra.setReceivePhone(addAddressRequest.getReceivePhone());
            userExtraMapper.insert(userExtra);
        } else {
            //更新
            userExtra.setReceiveName(addAddressRequest.getReceiveName());
            userExtra.setReceivePhone(addAddressRequest.getReceivePhone());
            userExtraMapper.updateAddress(userExtra);
        }
        return Rs.success();
    }

    @GetMapping("get-info")
    public Rs<UserInfoResponse> getUserInfo() {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        String userId = JwtUtil.getUserId();
        UserExtra userExtra = userExtraMapper.selByUserId(userId);
        if (userExtra != null) {
            userInfoResponse.setReceiveName(userExtra.getReceiveName());
            String receivePhone = userExtra.getReceivePhone();
            userInfoResponse.setReceivePhone(receivePhone);

        }
        return Rs.success(userInfoResponse);
    }
}
